package cn.wolfcode.shop.cloud.service.impl;


import cn.wolfcode.shop.cloud.common.BusinessException;
import cn.wolfcode.shop.cloud.domain.User;
import cn.wolfcode.shop.cloud.mapper.UserMapper;

import cn.wolfcode.shop.cloud.redis.MemberKeyPrefix;
import cn.wolfcode.shop.cloud.redis.RedisService;
import cn.wolfcode.shop.cloud.service.IUserService;
import cn.wolfcode.shop.cloud.util.MD5Util;
import cn.wolfcode.shop.cloud.util.MemberCodeMsg;
import cn.wolfcode.shop.cloud.vo.LoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;


@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Override
    public User get(Long id) {
        return userMapper.get(id);
    }
    @Autowired
    private RedisService redisService;
    @Override
    public String login(LoginVO loginVO) {
        //13088889999  123456

        //根据账号判断数据库是否有数据
        User user = userMapper.get(Long.parseLong(loginVO.getUsername()));
       //判断账号不能为空
        if(user == null){
            throw new BusinessException(MemberCodeMsg.LOGIN_FAIL);
        }

        //对比密码
        String pass = MD5Util.encode(loginVO.getPassword(), user.getSalt());

        if(!pass.equals(user.getPassword())){
            throw new BusinessException(MemberCodeMsg.LOGIN_FAIL);
        }

//放到redis中
        String token = createToekn(user);
        return token;
    }
   private String createToekn(User user) {
        String token = UUID.randomUUID().toString().replace("-", "");
        //MemberKeyPrefix.USER_TOKEN前缀    key：token value:user
        redisService.set(MemberKeyPrefix.USER_TOKEN,token, user);
        return token;
    }

    @Override
    public boolean refreshTime(String token) {
        //1 判断之前redis有没有token
        if(redisService.exists(MemberKeyPrefix.USER_TOKEN,token)){
            //2 如果有的话延长过期时间
            redisService.expire(MemberKeyPrefix.USER_TOKEN,token,MemberKeyPrefix.USER_TOKEN.getExpireTime());
            return true;
        }
        return false;
    }

    @Override
    public User getCurrentUser(String token) {
        if (!StringUtils.isEmpty(token)){
            return redisService.get(MemberKeyPrefix.USER_TOKEN,token,User.class);
        }
        return null;
    }


}
